package com.example.lianguisystem.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.example.lianguisystem.VO.DailyCapacityVO;
import com.example.lianguisystem.entity.SalesOrder;
import com.example.lianguisystem.entity.statistics.*;
import com.example.lianguisystem.mapperLianGui.DailyCapacityMapper;
import com.example.lianguisystem.service.DailyCapacityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class DailyCapacityServiceImpl implements DailyCapacityService {

    @Autowired
    private DailyCapacityMapper mapper;

    @Override
    public MnfFinished getMnfFinished(Date date, Integer mmBillid, Map<String, Object> userDataMap, String machine) {
        Map<String, Object> mmMap = mapper.selectMnfManuorderByBillid(mmBillid);
        MnfFinished mnfFinished = new MnfFinished();
        mnfFinished.setBillkind(1);
        mnfFinished.setBillstate(0);
        mnfFinished.setIotypeid(7);
        mnfFinished.setBilldate(date);
        mnfFinished.setWorkshopid((Integer) mmMap.get("workshopid"));
        mnfFinished.setOpid((Integer) userDataMap.get("opid"));
        mnfFinished.setShopid(0);
        mnfFinished.setQuantity(0.0);
        mnfFinished.setEmpid(null);
        mnfFinished.setDepartmentid(null);
        mnfFinished.setPrinttmpltid(null);
        mnfFinished.setCredid(null);
        mnfFinished.setAmount(0.0);
        mnfFinished.setUnitquantity(0.0);
        mnfFinished.setUnitprice(0.0);
        mnfFinished.setUnitqty1(0.0);
        mnfFinished.setUnitqty2(0.0);
        mnfFinished.setUnitqty3(0.0);
        mnfFinished.setExtqty(0.0);
        mnfFinished.setReferextqty(0.0);
        mnfFinished.setExpense(0.0);
        mnfFinished.setMaterial(0.0);
        mnfFinished.setExpenserefered(0);
        mnfFinished.setRefercount(0);
        mnfFinished.setRefercount(0);
        mnfFinished.setIoqty(0.0);
        mnfFinished.setUsetime(0.0);
        mnfFinished.setUserdef1(machine);
        mnfFinished.setUserdef2(null);
        mnfFinished.setUserdef3(null);
        mnfFinished.setUserdef4(null);
        mnfFinished.setUserdef5(null);
        mnfFinished.setUserdef6(null);
        mnfFinished.setUserdef7(null);
        mnfFinished.setUserdef8(null);
        mnfFinished.setUserdef9(null);
        mnfFinished.setUserdef10(null);
        mnfFinished.setUserdef11(null);
        mnfFinished.setUserdef12(null);
        mnfFinished.setUserdef13(null);
        mnfFinished.setUserdef14(null);
        mnfFinished.setUserdef15(null);
        mnfFinished.setUpdatetime(new Date());
        mnfFinished.setRemark("系统申请");
        mnfFinished.setSflag(0);
        return mnfFinished;
    }

    @Override
    public List<MnfFinisheditem> getMnfFinisheditem(Date date, List<SalesOrder> salesOrders) {
        List<MnfFinisheditem> mnfFinisheditemList = new ArrayList<>();
        for (int i = 1; i <= salesOrders.size(); i++) {
            SalesOrder salesOrder = salesOrders.get(i - 1);
            Map<String, Object> mmMap = mapper.selectMnfManuorderByBillid(salesOrder.getProcessingBillid());
            Map<String, Object> goodsMap = mapper.selectGoodsByCode(salesOrder.getDesignNo());
            MnfFinisheditem mnfFinisheditem = new MnfFinisheditem();
            mnfFinisheditem.setItemno(i);
            mnfFinisheditem.setStoreid(1);
            mnfFinisheditem.setGoodsid((Integer) mmMap.get("goodsid"));
            mnfFinisheditem.setPrice(0.0);
            mnfFinisheditem.setAprice(0.0);
            Double quantity = salesOrder.getCollectQty();
            mnfFinisheditem.setQuantity(quantity);
            mnfFinisheditem.setWasterqty(0.0);
            mnfFinisheditem.setUsetime(0.0);
            mnfFinisheditem.setEmpid(null);
            mnfFinisheditem.setAmount(0.0);
            mnfFinisheditem.setUnitid((Integer) goodsMap.get("unitid"));
            mnfFinisheditem.setUnitquantity(quantity);
            mnfFinisheditem.setUnitprice(0.0);
            mnfFinisheditem.setUnitqty1(quantity);
            mnfFinisheditem.setUnitqty2(0.0);
            mnfFinisheditem.setUnitqty3(0.0);
            mnfFinisheditem.setExtqty(0.0); //辅助数量
            mnfFinisheditem.setReferextqty(0.0);
            mnfFinisheditem.setExpense(0.0);
            mnfFinisheditem.setMaterial(0.0);
            mnfFinisheditem.setExpenserefered(0);
            mnfFinisheditem.setRefercount(0);
            mnfFinisheditem.setBatchcode(null);
            mnfFinisheditem.setProductdate(null);
            mnfFinisheditem.setValiddate(null);
            mnfFinisheditem.setReferbilltype(42); // 加工单
            mnfFinisheditem.setReferbillid((Integer) mmMap.get("billid"));
            mnfFinisheditem.setReferitemno(null);
            mnfFinisheditem.setReferbillcode((String) mmMap.get("billcode"));
            mnfFinisheditem.setUserdef1(null);
            mnfFinisheditem.setUserdef2(null);
            mnfFinisheditem.setUserdef3(null);
            mnfFinisheditem.setUserdef4(null);
            mnfFinisheditem.setUserdef5(null);
            mnfFinisheditem.setAssignqty(0.0);
            mnfFinisheditem.setAssignamount(0.0);
            mnfFinisheditem.setIoqty(0.0);
            mnfFinisheditem.setUserdef6(null);
            mnfFinisheditem.setUserdef7(null);
            mnfFinisheditem.setUserdef8(null);
            mnfFinisheditem.setUserdef9(null);
            mnfFinisheditem.setUserdef10(null);
            mnfFinisheditem.setUserdef11(null);
            mnfFinisheditem.setUserdef12(null);
            mnfFinisheditem.setUserdef13(null);
            mnfFinisheditem.setUserdef14(null);
            mnfFinisheditem.setUserdef15(null);
            mnfFinisheditem.setRemark((String) mmMap.get("remark"));
            mnfFinisheditem.setReferpassbillid(null);
            mnfFinisheditem.setReferpassitemno(null);
            mnfFinisheditemList.add(mnfFinisheditem);
        }
        return mnfFinisheditemList;
    }

    @Override
    public List<MnfFinisheddetail> getMnfFinisheddetail(List<MnfFinisheditem> mnfFinisheditemList) {
        List<MnfFinisheddetail> mnfFinisheddetailList = new ArrayList<>();
        for (int i = 1; i <= mnfFinisheditemList.size(); i++) {
            MnfFinisheditem mnfFinisheditem = mnfFinisheditemList.get(i - 1);
            List<Map<String, Object>> mmDetailList = mapper.selectMnfManuorderDetailByBillid(mnfFinisheditem.getReferbillid());
            for (int h = 1; h <= mmDetailList.size(); h++) {
                Map<String, Object> mmDetailMap = mmDetailList.get(h - 1);
                Integer goodsid = (Integer) mmDetailMap.get("goodsid");
                Map<String, Object> goodsMap = mapper.selectGoodsByGoodsid(goodsid);
                MnfFinisheddetail mnfFinisheddetail = new MnfFinisheddetail();
                mnfFinisheddetail.setItemno(mnfFinisheditem.getItemno());
                mnfFinisheddetail.setDetailno(h);
                mnfFinisheddetail.setGoodsid(goodsid);
                mnfFinisheddetail.setPrice(0.0);
                mnfFinisheddetail.setAprice(0.0);
                mnfFinisheddetail.setQuantity(0.0);
                mnfFinisheddetail.setAmount(0.0);
                mnfFinisheddetail.setUnitid((Integer) goodsMap.get("unitid"));
                mnfFinisheddetail.setUnitquantity(0.0);
                mnfFinisheddetail.setUnitprice(0.0);
                mnfFinisheddetail.setUnitqty1(0.0);
                mnfFinisheddetail.setUnitqty2(0.0);
                mnfFinisheddetail.setUnitqty3(0.0);
                mnfFinisheddetail.setExtqty(0.0);
                mnfFinisheddetail.setReferextqty(0.0);
                mnfFinisheddetail.setRefercount(0);
                mnfFinisheddetail.setBatchcode(null);
                mnfFinisheddetail.setProductdate(null);
                mnfFinisheddetail.setValiddate(null);
                mnfFinisheddetail.setReferbilltype(42);
                mnfFinisheddetail.setReferbillid((Integer) mmDetailMap.get("billid"));
                mnfFinisheddetail.setReferitemno((Integer) mmDetailMap.get("itemno"));
                mnfFinisheddetail.setReferqty(0.0);
                mnfFinisheddetail.setIoqty(0.0);
                mnfFinisheddetail.setAssignqty(0.0);
                mnfFinisheddetail.setAssignamount(0.0);
                mnfFinisheddetail.setBreferid(null);
                mnfFinisheddetail.setUserdef1(null);
                mnfFinisheddetail.setUserdef2(null);
                mnfFinisheddetail.setUserdef3(null);
                mnfFinisheddetail.setRemark("");
                mnfFinisheddetailList.add(mnfFinisheddetail);
            }
        }

        return mnfFinisheddetailList;
    }

    @Override
    public List<ICombin> getICombin(Map<String, Object> userDataMap, List<List<DailyCapacityVO>> collect) {

        List<Map<String, Object>> mapList = mapper.selectWorkshopMapDepartment();
        Map<String, Integer> workshopMapDepartment = new HashMap<>();
        for (Map<String, Object> map : mapList) {
            workshopMapDepartment.put((String) map.get("name"), (Integer) map.get("departmentid"));
        }
        List<ICombin> iCombinList = new ArrayList<>();
        for (List<DailyCapacityVO> dailyCapacityVOS : collect) {

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 2. 解析字符串为 LocalDate
            LocalDate now = LocalDate.parse(dailyCapacityVOS.get(0).getPrintDate2(), formatter);

            // 3. 转换为 Date 对象 (添加时区信息)
            Date date = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());

            Double quantity = 0.0;
            for (DailyCapacityVO dailyCapacityVO : dailyCapacityVOS) {
                quantity += dailyCapacityVO.getWeight();
            }
            DailyCapacityVO temp = dailyCapacityVOS.get(0);
            Map<String, Object> goodsMap = mapper.selectGoodsByCode(temp.getDesignNo());

            ICombin iCombin = new ICombin();
            iCombin.setBillkind(1);
            iCombin.setBillstate(0);
            iCombin.setBilldate(date);
            iCombin.setStoreid(1);
            Integer empId = mapper.selectEmpIdByName(dailyCapacityVOS.get(0).getPrintPerson());
            iCombin.setEmpid(empId);
            iCombin.setOpid((Integer) userDataMap.get("opid"));
            iCombin.setDepartmentid(workshopMapDepartment.get(temp.getWorkshop()));
            iCombin.setShopid(0);
            iCombin.setRefercount(0);
            iCombin.setGoodsid((Integer) goodsMap.get("goodsid"));
            iCombin.setQuantity(quantity);
            iCombin.setIoqty(0.0);
            iCombin.setBatchcode(null);
            iCombin.setValiddate(null);
            iCombin.setProductdate(null);
            iCombin.setUserdef1(temp.getMachine());
            iCombin.setUserdef2(null);
            iCombin.setUserdef3(null);
            iCombin.setUserdef4(null);
            iCombin.setUserdef5(null);
            iCombin.setUpdatetime(new Date());
            iCombin.setRemark("");
            iCombin.setSflag(0);
            iCombin.setUnitid((Integer) goodsMap.get("unitid"));
            iCombin.setUnitquantity(quantity);
            iCombin.setUnitqty1(quantity);
            iCombin.setUnitqty2(0.0);
            iCombin.setUnitqty3(0.0);
            iCombin.setExtqty(dailyCapacityVOS.size() * 1.0);
            iCombin.setReferextqty(0.0);
            iCombin.setUserdef6(null);
            iCombin.setUserdef7(null);
            iCombin.setUserdef8(null);
            iCombin.setUserdef9(null);
            iCombin.setUserdef10(null);
            iCombin.setUserdef11(null);
            iCombin.setUserdef12(null);
            iCombin.setUserdef13(null);
            iCombin.setUserdef14(null);
            iCombin.setUserdef15(null);
            iCombin.setProjectid(null);
            iCombin.setList(dailyCapacityVOS);
            iCombinList.add(iCombin);
        }

        return iCombinList;
    }

    @Override
    public Map<ICombin, List<ICombindetail>> getICombindetail(List<ICombin> iCombinList) {
        Map<ICombin, List<ICombindetail>> result = new HashMap<>();
        for (ICombin iCombin : iCombinList) {
            List<Map<String, Object>> bomMapList = mapper.selectJiaGongDanBom(iCombin.getGoodsid());
            if (bomMapList == null || bomMapList.size() < 0) {
                Map<String, Object> goodsMap = mapper.selectGoodsByGoodsid(iCombin.getGoodsid());
                throw new RuntimeException(goodsMap.get("name") + "未录入bom或未录入组装单专属bom");
            }
            List<ICombindetail> iCombindetailList = new ArrayList<>();
            Double totalAmount = 0.0;
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = LocalDate.now().format(dtf);


            Integer itemno = 2;
            for (int i = 0; i < bomMapList.size(); i++) {
                Map<String, Object> bomMap = bomMapList.get(i);
                List<Integer> hasDsList = new ArrayList<>();
                Double bomQuantity = ((BigDecimal) bomMap.get("quantity")).doubleValue();
                Double quantity = iCombin.getQuantity() * bomQuantity;
                getICombindetail(bomMap, format, quantity, iCombindetailList,hasDsList);
            }
            for (ICombindetail iCombindetail : iCombindetailList) {
                totalAmount += iCombindetail.getAmount();
            }
            iCombin.setAmount(totalAmount);
            double price = totalAmount / iCombin.getQuantity();
            iCombin.setPrice(price);
            iCombin.setUnitprice(price);
            result.put(iCombin, iCombindetailList);
        }
//        int i = 1 / 0;
        return result;
    }

    private void getICombindetail(Map<String, Object> bomMap, String format, Double totalQuantity, List<ICombindetail> iCombindetailList,List<Integer> hasDsList) {
        hasDsList.add((Integer) bomMap.get("goodsid"));
        BigDecimal kuChuQty = (BigDecimal) bomMap.get("kuChuQty");
        String shortname = (String) bomMap.get("shortname");
        if (kuChuQty.doubleValue() <= 0 && StrUtil.isNotBlank(shortname)) {
            Map<String, Object> goodsMap = mapper.selectGoodsByShortName(shortname, hasDsList);
            if (goodsMap == null) {
                addICombindetail(bomMap, format, totalQuantity, iCombindetailList);
                return;
            }
            goodsMap.put("UnitID", goodsMap.get("unitid"));
            goodsMap.put("elemgid", goodsMap.get("goodsid"));
            goodsMap.put("kuChuQty", goodsMap.get("qty"));
            getICombindetail(goodsMap, format, totalQuantity, iCombindetailList,hasDsList);
            return;
        }

        Map<String, Object> goodsMap = mapper.selectGoodsByShortName(shortname, hasDsList);
        Double quantity = totalQuantity;
        if (totalQuantity > kuChuQty.doubleValue() && StrUtil.isNotBlank(shortname) && goodsMap != null) {
            quantity = kuChuQty.doubleValue();
            totalQuantity = totalQuantity - kuChuQty.doubleValue();
        } else {
            quantity = totalQuantity;
            totalQuantity = 0.0;
        }
        addICombindetail(bomMap, format, quantity, iCombindetailList);
        if (totalQuantity > 0 && StrUtil.isNotBlank(shortname)) {
            goodsMap.put("UnitID", goodsMap.get("unitid"));
            goodsMap.put("elemgid", goodsMap.get("goodsid"));
            goodsMap.put("kuChuQty", goodsMap.get("qty"));
            getICombindetail(goodsMap, format, totalQuantity, iCombindetailList,hasDsList);
        }
    }

    private void addICombindetail(Map<String, Object> bomMap, String format, Double quantity,List<ICombindetail> iCombindetailList) {
        if (quantity <= 0) {
            return;
        }
        String shortname = (String) bomMap.get("shortname");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startDate = LocalDate.now().minusDays(7).format(dtf);
        Integer elemgid = (Integer) bomMap.get("elemgid");
        Double price = mapper.selectGoodsPriceByGoodsid(elemgid + "", format,startDate);
        if (price == null && StrUtil.isNotBlank(shortname)) {
            List<Map<String, Object>> maps = mapper.selectGoodsByShortNameOfAll(shortname);
            if (maps == null || maps.size() == 0) {
                String typeName = mapper.selectGdtypeName(elemgid);
                if (StrUtil.isBlank(typeName)) {
                    price = 6.0;
                } else {
                    throw new RuntimeException("结存单价为空");
                }
            }
            if (maps != null && maps.size() > 0) {
                for (Map<String, Object> goodsMap : maps) {
                    goodsMap.put("UnitID", goodsMap.get("unitid"));
                    goodsMap.put("elemgid", goodsMap.get("goodsid"));
                    goodsMap.put("kuChuQty", goodsMap.get("qty"));
                    elemgid = (Integer) goodsMap.get("elemgid");
                    price = mapper.selectGoodsPriceByGoodsid(elemgid + "", format,startDate);
                    if (price != null) {
                        bomMap = goodsMap;
                        break;
                    }
                }
            }
            if (price == null) {
                throw new RuntimeException("结存单价为空");
            }
        }
        ICombindetail iCombindetail = new ICombindetail();
        iCombindetail.setItemno(iCombindetailList.size() + 2);
        iCombindetail.setGoodsid(elemgid);
        iCombindetail.setBreferid(null);
        iCombindetail.setPrice(price);
        iCombindetail.setAprice(0.0);
        iCombindetail.setQuantity(quantity);
        Double amount = quantity * price;
        iCombindetail.setAmount(amount);
        iCombindetail.setUnitid((Integer) bomMap.get("UnitID"));
        iCombindetail.setUnitquantity(quantity);
        iCombindetail.setUnitprice(price);
        iCombindetail.setUnitqty1(quantity);
        iCombindetail.setUnitqty2(0.0);
        iCombindetail.setUnitqty3(0.0);
        iCombindetail.setExtqty(0.0);
        iCombindetail.setReferextqty(0.0);
        iCombindetail.setRefercount(0);
        iCombindetail.setReferqty(0.0);
        iCombindetail.setIoqty(0.0);
        iCombindetail.setBatchcode(null);
        iCombindetail.setProductdate(null);
        iCombindetail.setValiddate(null);
        iCombindetail.setReferbilltype(null);
        iCombindetail.setReferbillid(null);
        iCombindetail.setReferitemno(null);
        iCombindetail.setUserdef1(null);
        iCombindetail.setUserdef2(null);
        iCombindetail.setUserdef3(null);
        iCombindetail.setRemark(null);
        iCombindetail.setUserdef4(null);
        iCombindetail.setUserdef5(null);
        iCombindetail.setUserdef6(null);
        iCombindetail.setUserdef7(null);
        iCombindetail.setUserdef8(null);
        iCombindetail.setUserdef9(null);
        iCombindetail.setUserdef10(null);
        iCombindetail.setUserdef11(null);
        iCombindetail.setUserdef12(null);
        iCombindetail.setUserdef13(null);
        iCombindetail.setUserdef14(null);
        iCombindetail.setUserdef15(null);
        iCombindetail.setBarcodeid(null);
        iCombindetailList.add(iCombindetail);
    }
}
